<template>
  <!-- 数据层级比较深,判断有数据的时候再渲染 -->
  <div class="xtx-goods-page" v-if="detail.categories">
    <div class="container">
      <!-- 面包屑 -->
      <Bread separator="/">
        <!-- 默认插槽 -->
        <BreadItem to="/">首页</BreadItem>
        <!-- 一级分类 -->
        <BreadItem to="/">{{ detail.categories[1].name }}</BreadItem>
        <!-- 二级分类 -->
        <BreadItem to="/">{{ detail.categories[0].name }}</BreadItem>
        <!-- 二级分类下的商品 -->
        <BreadItem to="/">{{ detail.name }}</BreadItem>
      </Bread>
      <!-- 商品信息 -->
      <div class="goods-info">
        <!-- 新增结构 -->
        <!-- 图片预览区 -->
        <div class="media">
          <LeftImages :images="detail.mainPictures"></LeftImages>
          <!-- 销量组件 -->
          <GoodsSales></GoodsSales>
        </div>
        <!-- 商品信息区 -->
        <div class="spec">
          <!-- 信息组件 -->
          <GoodsName></GoodsName>
          <!-- sku组件 -->
          <GoodsSku :goods="detail" @change="selSku"></GoodsSku>
          <!-- 数量选择组件 -->
          <NumBox
            :min="1"
            :max="detail.inventory"
            v-model="buyNum"
            v-model:test="test"
          ></NumBox>
          <!-- v-model完整写法 -->
          <!-- <NumBox
            :modelValue="buyNum"
            @update:modelValue="buyNum = $event"
            :min="1"
            :max="detail.inventory"
          ></NumBox> -->
          <!-- 按钮组件 -->
          <Button @click="addCart" type="primary" style="margin-top: 20px"
            >加入购物车</Button
          >
        </div>
      </div>
      <!-- 商品详情 -->
      <div class="goods-footer">
        <div class="goods-article">
          <!-- 商品+评价 -->
          <div class="goods-tabs">
            <!-- 详情图片列表 -->
            <img
              v-imgLazy="url"
              v-for="url in detail.details.pictures"
              :key="url"
            />
          </div>
        </div>
        <!-- 24热榜+专题推荐 -->
        <div class="goods-aside"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, provide } from 'vue'
import { getGoods } from '@/api/goods'
import { useRoute } from 'vue-router'
// 左侧图片列表组件
import LeftImages from './components/goods-image.vue'
import GoodsSales from './components/goods-sale.vue'
import GoodsName from './components/goods-name.vue'
import msg from '@/components/Message/index.js'
import { useStore } from 'vuex'

const useDetailData = () => {
  // 获取商品详情数据
  const detail = ref({})
  // 注入数据 -> 在setup第一层注入数据,不需要放到getDetail函数中,因为是响应式数据
  provide('detail', detail)
  // 声明购买商品的数量
  const buyNum = ref(1)
  // 声明测试变量
  const test = ref(1)
  const route = useRoute()
  // console.log('vue3路由参数', route)
  const getDetail = async () => {
    const { result } = await getGoods(route.params.id)
    // console.log(result)
    detail.value = result
  }
  getDetail()

  return { detail, buyNum, test }
}

const useSkuSel = (detail) => {
  const currentSel = ref(null) // 存储当前选中的sku数据
  // sku选择回调函数
  const selSku = (skuInfo) => {
    console.log('选中的sku信息：', skuInfo)
    // 判断是否是有效sku信息,即不为空
    if (skuInfo.skuId) {
      // 显示选择之后的价格并更新库存
      detail.value.price = skuInfo.price
      detail.value.oldPrice = skuInfo.oldPrice
      detail.value.inventory = skuInfo.inventory

      currentSel.value = skuInfo
    } else {
      // 清除上次选择
      currentSel.value = null
    }
  }

  return { currentSel, selSku }
}

const useAddCart = (currentSel, detail, buyNum) => {
  // 加入购物车
  const store = useStore()
  const addCart = async () => {
    /**
       * 加入购物车需要满足的条件
       * 1.必须选择所有的sku属性 -> 产生有效的sku属性
       * 2.有效的sku商品数据库存大于0
       */
    if (!currentSel.value) {
      return msg({ text: '请选择商品sku属性' })
    }
    if (currentSel.value.inventory === 0) {
      return msg({ text: '商品库存为0' })
    }
    // console.log('添加进购物车')
    // 当前要存进购物车的商品数据
    const currentGood = {
      id: detail.value.id,
      name: detail.value.name,
      picture: detail.value.mainPictures[0],
      skuId: currentSel.value.skuId, // sku属性Id(唯一)
      price: currentSel.value.oldPrice, // 价格
      nowPrice: currentSel.value.price,
      attrsText: currentSel.value.specsText,
      stock: currentSel.value.inventory, // 库存
      selected: true, // 是否在购物车中选中
      isEffective: true, // 是否是有效商品
      count: buyNum.value // 购买数量
    }
    try {
      const res = await store.dispatch('cart/addCart', currentGood)
      // console.log(res)
      msg({ text: res, type: 'success' })
    } catch (error) {
      // console.log(error)
      msg({ text: '加入购物车失败', type: 'error' })
    }
  }

  return { addCart }
}

export default {
  name: 'XtxGoodsPage',
  components: {
    LeftImages,
    GoodsSales,
    GoodsName
  },
  setup () {
    const { detail, buyNum, test } = useDetailData()
    const { currentSel, selSku } = useSkuSel(detail)
    const { addCart } = useAddCart(currentSel, detail, buyNum)
    return { detail, selSku, buyNum, test, addCart }
  }
}
</script>

<style scoped lang='less'>
.goods-info {
  min-height: 600px;
  background: #fff;
  display: flex;
  // 新增样式
  .media {
    width: 580px;
    height: 600px;
    padding: 30px 50px;
  }
  .spec {
    flex: 1;
    padding: 30px 30px 30px 0;
  }
}
.goods-footer {
  display: flex;
  margin-top: 20px;
  .goods-article {
    width: 940px;
    margin-right: 20px;
  }
  .goods-aside {
    width: 280px;
    min-height: 1000px;
    background: #fff;
  }
}
.goods-tabs {
  min-height: 600px;
  background: #fff;
  img {
    width: 100%;
  }
}
.goods-warn {
  min-height: 600px;
  background: #fff;
  margin-top: 20px;
}
</style>
